package handler

import (
	"github.com/gin-gonic/gin"
	"github.com/juexin/gin-base/internal/service"
	"github.com/juexin/gin-base/pkg/response"
)

type AuthHandler struct {
	authService *service.AuthService
}

func NewAuthHandler(authService *service.AuthService) *AuthHandler {
	return &AuthHandler{
		authService: authService,
	}
}

// SetPassword 设置密码
func (h *AuthHandler) SetPassword(c *gin.Context) {
	var req service.SetPasswordRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "参数错误")
		return
	}

	// 从JWT token中获取用户ID
	userID := c.GetUint("user_id")
	if userID == 0 {
		response.Error(c, 1001, "用户未认证")
		return
	}

	err := h.authService.SetPassword(userID, &req)
	if err != nil {
		response.Error(c, 1001, err.Error())
		return
	}

	response.SuccessWithMsg(c, "密码设置成功", nil)
}

// Login 登录
func (h *AuthHandler) Login(c *gin.Context) {
	var req service.LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "参数错误")
		return
	}

	resp, err := h.authService.Login(&req)
	if err != nil {
		response.Error(c, 1002, err.Error())
		return
	}

	response.Success(c, resp)
}

// GetUserInfo 获取用户信息
func (h *AuthHandler) GetUserInfo(c *gin.Context) {
	userID := c.GetUint("user_id")

	user, err := h.authService.GetUserInfo(userID)
	if err != nil {
		response.Error(c, 1003, "获取用户信息失败")
		return
	}

	response.Success(c, user)
}
